const amqp = require('amqplib')

let channel = null

async function connectRabbitMQ() {
  if (channel) return channel
  const connection = await amqp.connect('amqp://localhost') // RabbitMQ 地址
  channel = await connection.createChannel()
  return channel
}
//发动消息
async function sendToQueue(queue, msg) {
  const ch = await connectRabbitMQ()
  await ch.assertQueue(queue, { durable: true })
  ch.sendToQueue(queue, Buffer.from(msg))
}
//接收消息
async function consumeQueue(queue, onMessage) {
  const ch = await connectRabbitMQ()
  await ch.assertQueue(queue, { durable: true })
  ch.consume(queue, (msg) => {
    if (msg !== null) {
      onMessage(msg.content.toString())
      ch.ack(msg)
    }
  })
}

module.exports = { sendToQueue, consumeQueue }
